package servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;

/**
 * Servlet implementation class RegistServlet
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String uName = request.getParameter("uName");
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");
        UserDao udao;

        if(uName.equals(""))
            request.setAttribute("nameErrorMess", "用户名不能为空！");

        if(password1.equals(""))
            request.setAttribute("password1ErrorMess", "密码不能为空！");

        if(!password1.equals(password2))
            request.setAttribute("password2ErrorMess", "您输入的密码不一致！");

        Enumeration<String> attNameList = request.getAttributeNames();
        if(!attNameList.hasMoreElements()) {
            udao = new UserDao();
            if(udao.queryByName(uName) == null) {
                udao.insert(uName, password1);
                request.setAttribute("registSuccessMess", "注册成功，请登录！");
                request.getRequestDispatcher("index.jsp").forward(request, response);
                return;
            }else
                request.setAttribute("registErrorMess", "您输入的用户名已被使用了！");
        }
        request.getRequestDispatcher("regist.jsp").forward(request, response);
    }

}
